// http.js
import Vue from 'vue'
export default {
  request_notoken(method, url, data, header) {
    // console.log(method, config.baseUrl+url, data, header);
    return new Promise((resolve, reject) => {
      uni.request({
        url: Vue.prototype.$baseUrl + url,
        method: method,
        data: data,
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          'Content-Type': 'application/json',
        },
        sslVerify: false,
        success: (res) => {
          // 这里可以对响应数据进行处理，例如判断状态码等
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  },
  request(method, url, data, header) {
    if (!header || !header.Authorization) {
      let token = uni.getStorageSync("token");
      header = {
        Authorization: "Token " + token,
      };
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: Vue.prototype.$baseUrl + url,
        method: method,
        data: data,
        header: header,
        sslVerify: false,
        success: (res) => {
          // 这里可以对响应数据进行处理，例如判断状态码等
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  },

  // 以下接口不再使用
  request_file(url, fileUrl, header) {
    if (!header || !header.Authorization) {
      let token = uni.getStorageSync("token");
      header = {
        Authorization: "Token " + token,
      };
    }

    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: Vue.prototype.$baseUrl + url,
        // filePath: file.url,
        filePath: fileUrl,
        name: "main_image",
        header: header,
        formData: {},
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  },

  update_main_image_notused(url, file, bMain) {
    let token = uni.getStorageSync("token");

    return new Promise((resolve, reject) => {
      const mimeTypes = {
        jpg: "image/jpeg",
        jpeg: "image/jpeg",
        png: "image/png",
        gif: "image/gif",
      };

      let fileExtension = file.url.split(".").pop();
      let mimeType = mimeTypes[fileExtension] || "application/octet-stream";
      console.log(mimeType);
      

      let image_type = "main_image";
      if (!bMain) {
        image_type = "other_images";
      }

      let uploadurl = Vue.prototype.$baseUrl + url;
      let formData = new FormData();
      if (file.url.startsWith("file://")) {
        console.log(uploadurl,file.url);
        plus.io.resolveLocalFileSystemURL(
          file.url,
          function (entry) {
            // 成功获取文件对象
            // console.log("File name:", entry.name);
            entry.file(
              function (file) {
                var reader = new plus.io.FileReader();
                reader.onloadend = function (e) {
                  // 这里的e.target.result是文件内容
                //   console.log("File content:", e.target.result);
            let fileObject = new File([e.target.result], file.name, { type: mimeType });
				  formData.set(image_type, fileObject);
					console.log(fileObject);

					// 创建 XMLHttpRequest 对象
					let xhr = new XMLHttpRequest();
					// 设置请求类型为 PATCH，以及请求的URL
					xhr.open("PATCH", uploadurl, true);
					xhr.setRequestHeader("Authorization", `Token ${token}`);

					// 设置请求完成的回调函数
					xhr.onload = function () {
						if (xhr.status === 200) {
							// 请求成功，解析响应数据
							resolve(JSON.parse(xhr.responseText));
						} else {
							// 请求失败
							reject(new Error("上传失败，状态码：" + xhr.status));
						}
					};
					// 设置请求失败的回调函数
					xhr.onerror = function () {
						reject(new Error("网络错误或服务器无响应"));
					};
					// 设置 sslVerify: false
					xhr.sslVerify = false;
					// 发送请求
					xhr.send(formData);
                };
                reader.readAsText(file, "utf-8");
              },
              function (e) {
                console.error("Read file failed:", e.message);
              }
            );
          },
          function (e) {
            console.error("Resolve file URL failed:", e.message);
          }
        );
      } else {
        // 如果 file.url 是普通 URL，直接使用 fetch
        fetch(file.url)
          .then((res) => res.blob())
          .then((blob) => {
            let fileObject = new File([blob], file.name, { type: mimeType });
            formData.set(image_type, fileObject);

            // 创建 XMLHttpRequest 对象
            let xhr = new XMLHttpRequest();
            // 设置请求类型为 PATCH，以及请求的URL
            xhr.open("PATCH", uploadurl, true);
            xhr.setRequestHeader("Authorization", `Token ${token}`);

            // 设置请求完成的回调函数
            xhr.onload = function () {
              if (xhr.status === 200) {
                // 请求成功，解析响应数据
                resolve(JSON.parse(xhr.responseText));
              } else {
                // 请求失败
                reject(new Error("上传失败，状态码：" + xhr.status));
              }
            };
            // 设置请求失败的回调函数
            xhr.onerror = function () {
              reject(new Error("网络错误或服务器无响应"));
            };
            // 设置 sslVerify: false
            xhr.sslVerify = false;
            // 发送请求
            xhr.send(formData);
          })
          .catch((error) => {
            reject(new Error("无法处理文件：" + error.message));
          });
      }
    });
  },
};
